<template>
  <div class="vue-box" style="display: none;" :style="'display: block;'">
    <el-dialog v-bind="$attrs"
               :visible.sync="dialogVisible"
               :append-to-body="true"
               top="8vh"
               :close-on-click-modal="false"
               v-on="$listeners" @open="onOpen" @close="onClose" :title="dialogTitle">
      <el-row :gutter="15">
        <el-form ref="elForm" :model="formData" :rules="rules" size="small" label-width="100px">
          <el-col :span="12">
            <el-form-item label="任务名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入任务名称" :maxlength="20" show-word-limit
                        clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="bean名称" prop="beanName">
              <el-autocomplete
                  class="inline-input"
                  v-model="formData.beanName"
                  :fetch-suggestions="beanNameSearch"
                  placeholder="请输入bean名称" :maxlength="20" show-word-limit
                  clearable :style="{width: '100%'}"
                  @select="beanNameSelect"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="方法参数" prop="params">
              <el-input v-model="formData.params" placeholder="请输入方法参数" :maxlength="80" show-word-limit
                        clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="cron表达式" prop="cronExpression">
              <el-autocomplete
                  class="inline-input"
                  v-model="formData.cronExpression"
                  :fetch-suggestions="cronExpressionSearch"
                  placeholder="请输入cron表达式" :maxlength="20" show-word-limit
                  clearable :style="{width: '100%'}"
                  @select="cronExpressionSelect"
              >
                <template slot-scope="{ item }">
                  <div class="name">{{ item.value }}</div>
                  <div style="font-size: 12px;">{{ item.desc }}</div>
                </template>
              </el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务状态" prop="status" required>
              <el-switch v-model="formData.status" active-text="运行" inactive-text="暂停"
                         inactive-color="#F90D0D" :active-value='0' :inactive-value='1'></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注文本" prop="remark">
              <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注文本" :maxlength="200"
                        show-word-limit :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </div>
    </el-dialog>
    <div class="c-panel">
      <!-- ------------- 检索参数 ------------- -->
      <div class="c-title">任务管理</div>
      <!-- ------------- 快捷按钮 ------------- -->
      <div class="fast-btn">
        <el-button type="primary" icon="el-icon-plus" @click="dialogVisible = true;dialogTitle='新增任务'">
          新增
        </el-button>
        <div class="c-item">
          <el-input
              placeholder="输入关键字进行过滤"
              v-model="p.name"
              clearable>
          </el-input>
        </div>
      </div>
      <el-table
          :border="true"
          resizable
          ref="userTable"
          :data="tableData"
          style="width: 100%"
          highlight-current-row
          max-height="450">
        <el-table-column type="selection" width="40" align="center"></el-table-column>
        <el-table-column
            prop="name"
            min-width="50"
            label="任务名称">
        </el-table-column>
        <el-table-column
            prop="beanName"
            min-width="80"
            label="bean名称">
        </el-table-column>
        <el-table-column
            prop="params"
            min-width="60"
            label="参数">
        </el-table-column>
        <el-table-column
            prop="cronExpression"
            min-width="60"
            label="cron表达式">
        </el-table-column>
        <el-table-column
            min-width="100"
            label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" :disabled="!sa.$sys.isAuth('task:update-status')"  @change="change($event,scope.row.id)" active-text="运行"
                       inactive-text="暂停"
                       inactive-color="#F90D0D" :active-value='0' :inactive-value='1'></el-switch>
          </template>
        </el-table-column>
        <el-table-column
            prop="createTime"
            min-width="80"
            label="创建时间">
        </el-table-column>
        <el-table-column
            prop="remark"
            min-width="80"
            label="备注">
        </el-table-column>
        <el-table-column
            fixed="right"
            width="120"
            label="操作">
          <template slot-scope="scope">
            <el-popover
                placement="left"
                width="600"
                @show="show(scope.row.id)"
                :open-delay="200"
                :close-delay="200"
                trigger="hover">
              <el-descriptions title="任务详情" size="medium">
                <el-descriptions-item label="bean名称">{{ showData.beanName }}</el-descriptions-item>
                <el-descriptions-item label="参数">{{ showData.params }}</el-descriptions-item>
                <el-descriptions-item label="cron表达式">{{ showData.cronExpression }}</el-descriptions-item>
                <el-descriptions-item label="状态">
                  <el-tag v-if="showData.status === 0">运行</el-tag>
                  <el-tag type="danger" v-else>暂停</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="备注">{{ showData.remark }}</el-descriptions-item>
              </el-descriptions>
              <el-button slot="reference" type="text">查看</el-button>
            </el-popover>
            <el-button type="text" @click="showLog(scope.row.id)">运行日志</el-button>
            <el-button
                @click.native.prevent="run(scope.row.id)"
                type="text">
              运行一次
            </el-button>
            <el-button
                @click.native.prevent="edit(scope.row.id)"
                type="text">
              编辑
            </el-button>
            <el-popconfirm
                title="确认移除？移除后无法恢复！！"
                @confirm="del(scope.row.id)"
            >
              <el-button
                  slot="reference"
                  type="text">
                移除
              </el-button>
            </el-popconfirm>

          </template>
        </el-table-column>
      </el-table>
      <div class="page-box">
        <el-pagination background
                       layout="total, prev, pager, next, sizes, jumper"
                       :current-page.sync="p.current"
                       :page-size.sync="p.size"
                       :total="p.total"
                       :page-sizes="[10, 20, 30, 40, 50, 100]"
                       @current-change="f5()"
                       @size-change="f5()">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
let PATH = "/task"
module.exports = {
  components: {},
  watch: {
    'p.name': function (val) {
      this.f5()
    }
  },
  data() {
    return {
      restaurants: [],
      cronList: [],
      tableData: [],
      p: {
        name: '',
        current: 1,
        size: 10,
        total: -1
      },
      showData: {
        name: undefined,
        beanName: undefined,
        params: undefined,
        cronExpression: undefined,
        status: 1,
        remark: undefined,
      },
      formData: {
        name: undefined,
        beanName: undefined,
        params: undefined,
        cronExpression: undefined,
        status: 1,
        remark: undefined,
      },
      rules: {
        name: [{
          required: true,
          message: '请输入任务名称',
          trigger: 'blur'
        }],
        beanName: [{
          required: true,
          message: '请输入bean名称',
          trigger: 'change'
        }],
        params: [{
          required: false,
          message: '请输入方法参数',
          trigger: 'blur'
        }],
        cronExpression: [{
          required: true,
          message: '请输入cron表达式',
          trigger: 'change'
        }],
        remark: [],
      },
      dialogVisible: false,
      dialogTitle: ''
    }
  },
  methods: {
    beanNameSelect(item) {
      this.formData.beanName = item.value
    },
    beanNameSearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      cb(results);
    },
    cronExpressionSelect(item) {
      this.formData.cronExpression = item.value
    },
    cronExpressionSearch(queryString, cb) {
      var restaurants = this.cronList;
      var results = queryString ? restaurants.filter(this.createFilter2(queryString)) : restaurants;
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1);
      };
    },
    createFilter2(queryString) {
      return (restaurant) => {
        return (restaurant.desc.toLowerCase().indexOf(queryString.toLowerCase()) !== -1 ||
            restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1
        );
      };
    },
    /*i跳转页面查看日志*/
    showLog(id) {
      // 数据库中任务日志菜单的ID,
      let viewId = 'task-log';
      // 显示任务日志界面调用这个方法后记得使用setTimeout()来执行接下来的操作，
      // 多窗口通信，不限这种方法，这种方法不需要改动调用界面，慢慢领悟害
      sa_admin.showMenuById(viewId);
      setTimeout(() => {
        let app = sa_admin.getTabWindow(viewId);
        app.p.jobId = id;
        app.f5()
      }, 100)


    },
    edit(id) {
      sa.ajax(PATH + "/get", {id: id}, (res) => {
        this.formData = res.data
        this.dialogVisible = true
        this.dialogTitle = '编辑任务'
      }, {type: 'get', msg: null})
    },
    run(id) {
      sa.ajax(PATH + "/run", {id: id}, (res) => {
        sa.msgOk(res.msg, () => {
        })
      }, {type: 'get', msg: null})
    },
    change(status, id) {
      sa.ajax(PATH + "/update-status", {id: id, status: status}, (res) => {
        sa.msgOk(res.msg, () => {
          this.f5()
        })
      }, {msg: null})
    },
    del(id) {
      sa.ajax(PATH + "/del", {id: id}, (res) => {
        sa.alert(res.msg, () => {
          this.f5()
        })
      }, {})
    },
    show(id) {
      sa.ajax(PATH + "/get", {id: id}, (res) => {
        this.showData = res.data
      }, {type: 'get', msg: null})
    },
    onOpen() {
      sa.ajax(PATH + "/init-form", {}, (res) => {
        this.restaurants = res.data.beanNameList;
        this.cronList = res.data.cronList;
      }, {type: 'get', msg: null})
    },
    onClose() {
      this.formData = {
        name: undefined,
        beanName: undefined,
        params: undefined,
        cronExpression: undefined,
        status: 1,
        remark: undefined,
      }
      this.$refs['elForm'].resetFields()
    },
    close() {
      this.dialogVisible = false
    },
    handelConfirm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        sa.ajax(PATH + "/save-or-update", this.formData, (res) => {
          sa.alert(res.msg, () => {
            this.close()
            this.f5();
          })
        }, {})
      })
    },
    f5() {
      sa.ajax(PATH + "/list", this.p, (res) => {
        this.tableData = res.data;
        this.p.total = res.dataCount
      }, {type: 'get'})
    }
  },
  mounted() {
  },
  created() {
    this.f5()
  }
}
</script>

<style scoped>
</style>
